<?php
/**
 * lemocms
 * ============================================================================
 * 版权所有 2018-2027 lemocms，并保留所有权利。
 * 网站地址: https://www.lemocms.com
 * ----------------------------------------------------------------------------
 * 采用最新Thinkphp6实现
 * ============================================================================
 * Author: yuege
 * Date: 2019/9/4
 */
namespace app\admin\controller\wechat;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use app\common\model\WxAccount;
use lemo\service\WechatApp;
use lemo\helper\DataHelper;

use app\common\model\WxFans;
use app\common\model\WxMaterial;
use app\common\model\WxMaterialInfo;
use app\common\model\WxMsgHistory;
use app\common\model\WxReply;
use app\common\model\WxTag;

use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Article;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Video;
use EasyWeChat\Kernel\Messages\Voice;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;

class Wechat extends Backend {
    //图片（image）: 2M，支持bmp/png/jpeg/jpg/gif格式
    //
    //语音（voice）：2M，播放长度不超过60s，mp3/wma/wav/amr格式
    //
    //视频（video）：10MB，支持MP4格式
    //
    //缩略图（thumb）：64KB，支持JPG格式
    protected $imageValidate = [
        'image' => 'filesize:2048|fileExt:jpg,png,gif,jpeg'

    ];
    protected $videoValidate = [
        'file' => 'filesize:10240|fileExt:avi,rmvb,3gp,flv,mp4,rm'

    ];
    protected $voiceValidate = [
        'file' => 'filesize:2048|fileExt:mp3,wma,wav,amr'

    ];
    protected $thumbValidate = [
        'image' => 'filesize:64|fileExt:jpg'

    ];
    protected $where =[];
    public $wechatApp;
    public $store_id;
    protected $wechatAccount ;
    protected $materialType = ['news','video','voice','image','music'];
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated
        $wechatApp  = new WechatApp();
        $this->store_id = $wechatApp->store_id;
        $this->wechatAccount = WxAccount::where('status',1)->where('store_id',$this->store_id)->find();

        if($this->wechatAccount){
            $this->wechatApp = cache('wechatapp_'.$this->wechatAccount->id);
            if(!$this->wechatApp){
                $this->wechatApp = $wechatApp->wechatApp;
//                cache('wechatapp_'.$this->wechatAccount->id,$this->wechatApp);
            }
            $this->where= ['store_id'=>$this->store_id,'wx_aid'=>$this->wechatAccount->id];

        }else{
            $this->wechatAccount = WxAccount::where('store_id',$this->store_id)->find();
        }
    }



    /**
     ************************公众号管理****************************
     */
    public function index(){
        if (Request::isPost()) {
            $list = Db::name('wx_account')->alias('a')
                ->leftJoin('wx_type t','t.type_id=a.type')
                ->field('a.*,t.name as type_name')->cache(3600)
                ->select()->toArray();

            return $result = ['code' => 0, 'msg' =>lang('get info success'), 'data' => $list,];
        }
        return view();

    }

    public function add(){
        if (Request::isPost()) {
            $data = Request::post();
            try{
                $this->validate($data, 'WxAccount');
            }catch (\Exception $e){
                $this->error($e->getMeussage());
            }
            $data['weixin'] = $data['wxname'];
            $res = WxAccount::create($data);
            if ($res) {
                $this->success(lang('add success'),url('index'));
            } else {
                $this->error(lang('add fail'));
            }
        }
        $view = [
            'info' => '',
            'title' => lang('add'),
        ];
        View::assign($view);
        return view();
    }

    public function edit(){
        if (Request::isPost()) {
            $data = Request::post();
            try {
                $this->validate($data, 'WxAccount');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $res = WxAccount::update($data);
            if ($res) {
                $this->success(lang('edit success'), url('index'));
            } else {
                $this->error(lang('edit fail'));
            }
        }
        $info = WxAccount::cache(3600)->find(Request::get('id'));
        $view = [
            'info' => $info,
            'title' => '修改',
        ];
        View::assign($view);
        return view('add');

    }
    public function state(){

        $id = Request::post('id');
        if($id){
            $info = WxAccount::cache(3600)->find($id);
            $info->status = $info->status==1?0:1;
            if($info->status==1){
                $list = WxAccount::where('status',1)->where('id','<>',$info->id)->select();
                if($list){
                    foreach ($list as $k=>$v){
                        $v->status=0;
                        $v->save();
                    }
                }
            }
            $info->save();
            $this->success(lang('edit success'));
        }else{
            $this->error('非法数据');
        }
    }
    public function delete(){
        $id = Request::post('id');
        if($id){
            WxAccount::destroy($id);
            $this->success(lang('delete success'));

        }else{
            $this->error('非法数据');
        }

    }


    /**
     ************************菜单管理****************************
     */


    public function menu(){
        $baseURL = Request::domain();
        $view = [
            'baseURL'=>$baseURL,
        ];
        View::assign($view);
        return view();

    }
    //获取微信账号
    public function getWxAccount(){

        $info =  WxAccount::cache(3600)->order('status desc')->select();

        return $info;

    }
    //更改app
    public function changeApp(){
        $appid = Request::post('app_id');
        $isAPP = WxAccount::cache(3600)->where('app_id',$appid)->value('status');
        $button['button']=[];
        if(!$isAPP){
            $this->error('失败','',$button);
        }
        //获取当前菜单
        $menu = cache('wx_menus');
        if(!$menu){

            $menu = $this->wechatApp->menu->list();
            cache('wx_menus',$menu);
        }
        if(isset($menu['menu'])){

            $button = $menu['menu'];
            $this->success('成功','',$button);
        }else{
            $this->error('失败','',$button);
        }

    }

    // 添加微信菜单
    public function addWeixinMenu(){
        $data = Request::post();
        $app_id = $data['app_id'];
        $isApp = WxAccount::where('store_id',$this->store_id)->cache(3600)->where('app_id',$app_id)->value('status');
        if($isApp !=1){
            $this->error(lang('account is not accessed'));
        }
        $menu = $data['menu'];
        if (!empty($menu)) {
            $res = $this->wechatApp->menu->create($menu['button']);
            if($res['errcode']==0){
                $this->success(lang('add success'));
                //WxMenu::create($menu['button']);
            }else{
                $this->error(lang('create fai'));
            }
        }
        $this->error(lang('create fai'));
    }

    public function updataWechatMenu()
    {
        $menu =  $this->wechatApp->menu->list();
        $this->success(lang('update success'));

    }
    public function menuDel(){

        $res = $this->wechatApp->menu->delete(); // 全部
        if($res['errcode']==0){
            $this->success(lang('delete success'));
        }else{
            $this->error(lang('delete fai'));
        }
    }

    /**
     ************************粉丝管理***************************
     */
    public function fans(){

        if (Request::isPost()) {
            $wx_aid = Request::post('wx_aid');
            if(!$wx_aid){
                $wx_aid =  $this->wechatAccount->id;
            }
            if(!$wx_aid){
                return $result = ['code' => 0,'msg' => lang('account is not accessed'),];
            }
            $keys = Request::post('keys','','trim');
            $page = Request::post('page') ? Request::post('page') : 1;
            $list=WxFans::where('nickname','like','%'.$keys.'%')
                ->where('wx_aid',$wx_aid)
                ->order('fans_id desc')->cache(3600)
                ->paginate(['list_rows' => $this->pageSize, 'page' => $page])
                ->toArray();
            $tag = WxTag::where('store_id',$this->store_id)->where('wx_aid',$wx_aid)
                ->select()->toArray();

            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['tag_list'] = $tag;
            }
            return $result = ['code' => 0, 'msg' =>lang('get info success'), 'data' => $list['data'],'count'=>$list['total'],'tag'=>$tag];
        }
        $wxAccount = WxAccount:: where('store_id',$this->store_id)->select();
        $view = [
                'title'=>'粉丝',
                'info'=>'',
                'wxAccount'=>$wxAccount,
            ];
        View::assign($view);
        return view();
    }


    public function fansAysn(){
        $wx_aid = Request::post('wx_aid');
        if(!$wx_aid){
            $this->error('请求错误');
        }
        $wxAccount = $this->wechatAccount;
        if(!$wxAccount){
            $this->error(lang('account is not accessed'));
        }
        $usersOpenidList = $this->wechatApp->user->list();
        $users = [];
        if($usersOpenidList['total']>0){
            foreach ($usersOpenidList['data']['openid'] as $k=>$v){
                $users[$k] =  $this->wechatApp->user->get($v);
            }
        }
        $WxFansModel = new WxFans();
//        Db::startTrans();
//        try {
            foreach ($users as $k=>$v){
                $v['wx_aid'] = $wx_aid;
                $v['tagid_list'] = json_encode($v['tagid_list']);

                $fans = $WxFansModel::where($this->where)
                    ->cache(3600)
                    ->where('openid',$v['openid'])
                    ->find();
                if($fans){
                    $v['update_time'] = time();
                    $res = $fans->force()->save($v);
                }else{
                    $v['store_id'] = $this->store_id;
                    $v['update_time'] = time();
                    $v['nickname_encode'] = json_encode($v['nickname']);
                    $res = $WxFansModel::create($v);
                }
            }

//          // 提交事务
//          Db::commit();
            $this->success('同步成功');
//        } catch (\Exception $e) {
//             //回滚事务
//            Db::rollback();
//            $this->error('同步失败');
//        }

//        $this->success('同步成功');

    }
    //粉丝标签
    public function fansTagGroup(){
        if(Request::isPost()){
            $id = Request::post('id');
            $tag = Request::post('tag');
            $wxFans = WxFans::where('fans_id',$id)->cache(3600)->find();
            $tags = WxTag::where('store_id',$this->store_id)
                ->where('wx_aid',$wxFans->wx_aid)->cache(3600)->find();
            $wxFans->tag = $tag;
            $res = $this->wechatApp->user_tag->tagUsers([$wxFans->openid],$tags['tag_id']);
            if($res){
                $wxFans->save();
                $this->success(lang('update success'));
            }else{
                $this->error(lang('update fail'));

            }
        }

    }
    //粉丝标签管理
    public function tag(){
        if (Request::isPost()) {
            $wx_aid = Request::post('wx_aid');
            if(!$wx_aid){
                $wx_aid =  $this->wechatAccount->id;
            }
            if(!$wx_aid){
                return $result = ['code' => 0,'msg' => lang('account is not accessed'),];

            }
            $keys = Request::post('keys','','trim');
            $page = Request::post('page') ? Request::post('page') : 1;
            $list=Db::name('wx_tag')
                ->where('name','like','%'.$keys.'%')
                ->where('wx_aid',$wx_aid)
                ->order('id desc')
                ->cache(3600)
                ->paginate(['list_rows' => $this->pageSize, 'page' => $page])
                ->toArray();

            return $result = ['code' => 0, 'msg' =>lang('get info success'), 'data' => $list['data'],'count'=>$list['total']];
        }


        $wxaccount = WxAccount::where('store_id',$this->store_id)->cache(3600)->select();

        $view = ['title'=>lang('tag'), 'info'=>'', 'wxaccount'=>$wxaccount];
        View::assign($view);
        return view();

    }
    public function tagState(){

        if (Request::isPost()) {
            $id = Request::post('id');
            if (empty($id)) {
                $this->error('id'.lang('not exist'));
            }
            $adv = WxTag::find($id);
            $status = $adv['status'] == 1 ? 0 : 1;
            $adv->status = $status;
            $adv->save();
            $this->success(lang('edit success'));
        }

    }
    public function tagAysn()
    {
        if(Request::isPost()){
            $wx_aid = $this->wechatAccount->id;
            $tags = $this->wechatApp->user_tag->list();

            foreach($tags['tags'] as $k=>$v){
                $info = WxTag::where('name',$v['name'])->find();
                $v['tag_id'] = $v['id'];

                if(!$info){
                    $v['store_id'] = $this->store_id;
                    $v['wx_aid'] = Request::post('wx_aid')?Request::post('wx_aid'):$wx_aid;
                    unset($v['id']);
                    WxTag::create($v);
                }else{
                    $v['id'] = $info['id'];
                    WxTag::update($v);

                }

            }
            $this->success(lang('aysn success'));

        }

        $this->error(lang('invalid options'));

    }
    
    public function tagAdd()
    {
        if(Request::isPost()){
            $data  = Request::post();
            if($data){
                $data['store_id'] = $this->store_id;
                $this->validate($data,'WxTag');

                $res = $this->wechatApp->user_tag->create($data['name']);
                $data['tag_id'] = $res['tag']['id'];
                if($res){
                    WxTag::create($data);
                    $this->success(lang('add success'));
                }else{
                    $this->error(lang('add fail'));
                }

            }else{
                $this->error(lang('add fail'));
            }


        }
        $wx_aid = Request::get('wx_aid');
        $view = [
            'title'=>lang('add'),
            'info'=>['wx_aid'=>$wx_aid],
        ];

        View::assign($view);
        return view('tag_add');
    }

    public function tagEdit()
    {
        if(Request::isPost()){
            $data  = Request::post();
            if($data){
                $data['store_id'] = $this->store_id;
                $tag = WxTag::find($data['id']);

                $res = $this->wechatApp->user_tag->update($tag['tag_id'],$data['name']);
                if($res['errcode']==0){
                    WxTag::update($data);
                    $this->success(lang('edit success'));
                }else{
                    $this->error(lang('edit fail'));
                }

            }else{
                $this->error(lang('edit fail'));
            }
        }
        $id = Request::get('id');
        $info  = WxTag::find($id);

        $view = [
            'title'=>'修改',
            'info'=>$info,
            'wx_aid'=>$info['wx_aid'],
        ];

        View::assign($view);
        return view('tag_add');

//        $this->wechatApp->user_tag->update($tagId, $name);
    }

    public function tagDel()
    {
        $id = Request::post('id');
        $info = WxTag::find($id);
        $res = $this->wechatApp->user_tag->delete($info['tag_id']);
        if($res['errcode']==0){
            WxTag::destroy($id);
        }else{
            $this->error(lang('delete fai'));
        }
        $this->success(lang('delete success'));

    }

    /**
     ************************历史消息管理***************************
     */

    public function message()
    {
        if(Request::isPost()){
            $keys = Request::post('keys','','trim');
            $page = Request::post('page') ? Request::post('page') : 1;
            $list=Db::name('wx_msg_history')
                ->where('store_id',$this->store_id)
                ->where('wx_aid',$this->wechatAccount->id)
                ->where('nickname','like','%'.$keys.'%')
                ->order('id desc')
                ->paginate(['list_rows' => $this->pageSize, 'page' => $page])
                ->toArray();

            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total']];
        }

        return view();
    }

    public function messageDel()
    {
        if(Request::isPost()){
            $id = Request::post('id');
            WxMsgHistory::destroy($id);
            $this->success(lang('delete success'));
        }

    }
    public function messageReply()
    {
        if(Request::isPost()){
            $material_id = Request::post('material_id');
            $openid = Request::post('openid');
            $msg_type = Request::post('msg_type');
            $material = WxMaterial::find($material_id);
            if($material){
                $media_id = $material->media_id;

            }else{
                $media_id = '';
            }
            $message = WxReply::where($this->where)->where('type','default')->value('data');

            switch ($msg_type) {
                case 'text':
                    $data = Request::post('data');
                    $message = new Text($data);
                    break;

                case 'image':
                    if(WxMaterial::where('media_id',$media_id)->find()){

                        $message =  new Image($media_id);
                    }
                    break;

                case 'news':
                    $new = WxMaterialInfo::where($this->where)->where('material_id', $material_id)->find();
                    if ($new) {
                        $newsList[] = new NewsItem([
                            'title' => $new->title,
                            'description' => $new->digest,
                            'url' => $new->url,
                            'image' => $new->cover,
                        ]);
                        $message = new News($newsList);
                    }else{
                        $message = WxReply::where($this->where)->where('type','default')->value('data');

                    }
                    break;
                case 'video':
                    if(WxMaterial::where('media_id',$media_id)->find()) {
                        $message =  new Video($media_id, $material->file_name, $material->des);
                    }
                    break;
                case 'voice':
                    if(WxMaterial::where('media_id',$media_id)->find()) {

                        $message =  new Voice($media_id);
                    }
                    break;
                default:
                    break;
            }

            $result = $this->wechatApp->customer_service->message($message)->to($openid)->send();

            if ($result['errcode'] == 0) {
                $this->success(lang('send success'));
            } else {
                $this->error(lang('send fail'));

            }
        }else{
            $wx_aid  = Request::get('wx_aid');
            $id  = Request::get('id');
            $info = WxMsgHistory::where('store_id',$this->store_id)->find($id);
            $user = $this->wechatApp->user->get($info->openid);
            $materialGroup = $this->getMaterialGroup();
            $view = ['title'=>lang('reply'),'user'=>$user,'info'=>$info,'materialGroup'=>$materialGroup];
            View::assign($view);
            return view();
        }

    }

    /**
     ************************素材管理***************************
     */
    public function material(){

        if (Request::isPost()) {
            $wx_aid = Request::post('wx_aid');
            if(!$wx_aid){
                $wx_aid = $this->wechatAccount->id;
            }
            if(!$wx_aid){
                return $result = ['code' => 0,'msg' => lang('account is not accessed'),];

            }
            $keys = Request::post('keys','','trim');
            $page = Request::post('page') ? Request::post('page') : 1;
            $list=Db::name('wx_material')
                ->where('nickname','like','%'.$keys.'%')
                ->where('wx_aid',$wx_aid)
                ->order('fans_id desc')
                ->paginate(['list_rows' => $this->pageSize, 'page' => $page])
                ->toArray();
            return $result = ['code' => 0, 'msg' =>lang('get info success'), 'data' => $list['data'],'count'=>$list['total']];
        }
        $materialGroup = $this->getMaterialGroup();
        $view = [
            'title'=>lang('material'),
            'info'=>'',
            'materialGroup'=>$materialGroup,
        ];
        View::assign($view);
        return view();


    }
    //添加图文素材
    public function materialAdd(){
        if(Request::isPost()){
            $data = Request::post('content');
            
            foreach ($data as $k => $v) {
                $article= new Article($data[$k]);
                $articles[$k] = $article;
            }
            $res = $this->wechatApp->material->uploadArticle($articles);
            $this->showError($res);
            $WxMaterialData = [
                'store_id'=>$this->store_id,
                'wx_aid'=>$this->wechatAccount->id,
                'type'=>'news',
                'media_id'=>$res['media_id'],
                ];

            $material =    $this->getMaterialByMediaId($res['media_id']);

            // 启动事务
            Db::startTrans();
            try {
                $mat= WxMaterial::create($WxMaterialData);
//                if(isset($data[0])){
                    //多图文
                    foreach ($data as $k=>$v) {

                        $data[$k]['cover'] = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value('media_url');
                        $data[$k]['local_cover'] = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value('local_cover');
                        $data[$k]['store_id'] = $this->store_id;
                        $data[$k]['wx_aid'] = $this->wechatAccount->id;
                        $data[$k]['url'] = $material['news_item'][$k]['url'];
                        $data[$k]['material_id'] = $mat->id;
                        $matinfo=  Db::name('WxMaterialInfo')->save($data[$k]);

                    }

                // 提交事务
                Db::commit();
                $this->success('成功');

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }
        }
        $params['name'] = 'container';
        $params['content'] = '';
        $view = [
            'info' => [],
            'title' => lang('add'),
            'ueditor'=>build_ueditor($params),
        ];
        View::assign($view);
        return view();
    }

    public function materialEdit(){
        if(Request::isPost()){
            $data = Request::post('content');
            $id = Request::post('mediaId');
            $mediaId = WxMaterial::where('id', $id)->value('media_id');

            foreach ($data as $k => $v) {

                $article = new Article($data[$k]);

                $res = $this->wechatApp->material->updateArticle($mediaId, $article, $k);

            }

            $this->showError($res);

            $material =  $this->getMaterialByMediaId($mediaId);

            // 启动事务
            Db::startTrans();
            try {
//
                    foreach ($data as $k=>$v) {
                        $data[$k]['id'] = WxMaterialInfo::where($this->where)->where('thumb_media_id', $v['thumb_media_id'])->value('id');
                        $data[$k]['cover'] = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value('media_url');
                        $data[$k]['store_id'] = $this->store_id;
                        $data[$k]['wx_aid'] = $this->wechatAccount->id;
                        $data[$k]['url'] = $material['news_item'][$k]['url'];
                        $data[$k]['material_id'] = $id;
                        $data[$k]['update_time'] = time();
                        $WxMaterialInfoModel = WxMaterialInfo::find($data[$k]['id']);
                        $r[$k] = $WxMaterialInfoModel->force()->save($data[$k]);
                    }

                // 提交事务
                Db::commit();
                $this->success('成功');

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $id = Request::get('id');
        $info = WxMaterialInfo::where('material_id',$id)->select()->toArray();
        $params['name'] = 'container';
        $params['content'] = '';
        $view = [
            'title'=>lang('edit'),
            'info'=>$info,
            'ueditor'=>build_ueditor($params),
        ];
        View::assign($view);

        return view('material_add');
    }

    //素材同步
    public function materialAysn(){
        if(Request::isPost()){
            $res = cache('materialList');
            if(!$res){
                $res = $this->wechatApp->material->list('news', 0, 50);
                cache('materialList',$res,3600);
            }
            $this->showError($res);
            foreach ($res['item'] as $k=>$v){
                $material = WxMaterial::where('media_id',$v['media_id'])->find();
                if(!$material){
                    $material = ['store_id'=>$this->store_id,
                        'wx_aid'=>$this->wechatAccount->id,
                        'media_id'=>$v['media_id'],
                        'media_url'=>$v['content']['news_item'][0]['thumb_url'],
                        'type'=>"news",
                        ];
                    $wxmater = WxMaterial::create($material);
                    foreach ($v['content']['news_item'] as $kk=>$vv){
                        $info = ['store_id'=>$this->store_id,
                            'wx_aid'=>$this->wechatAccount->wx_aid,
                            'material_id'=>$wxmater->id,
                            'thumb_media_id'=>$vv['thumb_media_id'],
                            'local_cover'=>$vv['thumb_url'],
                            'cover'=>$vv['thumb_url'],
                            'title'=>$vv['title'],
                            'author'=>$vv['author'],
                            'show_cover'=>$vv['show_cover_pic'],
                            'digest'=>$vv['digest'],
                            'content'=>$vv['content'],
                            'url'=>$vv['url'],
                            'content_source_url'=>$vv['content_source_url'],
                            'need_open_comment'=>$vv['need_open_comment'],
                            'only_fans_can_comment'=>$vv['only_fans_can_comment'],
                        ];
                        WxMaterialInfo::create($info);

                    }
                }
            }
            $this->success(lang('aysn success'));

        }else{

            $this->error(lang('invalid request'));
        }


    }
    public function materialDel(){

        $id = Request::post('id');
        $material = WxMaterial::find($id);
        //删除微信媒体库
        $this->wechatApp->material->delete($material->media_id);

        if($material['type']=='news'){
            $info = WxMaterialInfo::where($this->where)->where('material_id',$id)->delete();
            if($info && $material->delete()){
                $this->success(lang('delete success'));
            }else{
                $this->error(lang('delete fail'));

            }
        }else{
            if($material->delete()){

                $this->success(lang('delete success'));
            }else{
                $this->error(lang('delete fail'));

            }
        }

    }
    // 发送消息
    public function materialSend(){
        if (Request::isPost()) {
            $id = Request::post('id');
            $info = WxMaterial::find($id);
            $res = $this->sendAll($info);
            $this->showError($res);
            $this->success(lang('send success'));
        } else {
            $this->error(lang('send fail'));

        }

    }
    //预览消息

    public function materialPreview(){
        if(Request::isPost()){
            $wxname = Request::post('wxname');
            $id = Request::post('id');
            $info = WxMaterial::find($id);
            $res = $this->preview($info,$wxname);

            $this->showError($res);
            $this->success(lang('send success'));

        }else{
            $this->error(lang('send fail'));

        }


    }

    protected function preview($info,$wxname){

        // 发送预览群发消息给指定的 openId 用户
        //$this->wechatApp->broadcasting->previewText($text, $openId);
        //$this->wechatApp->broadcasting->previewNews($mediaId, $openId);
        //$this->wechatApp->broadcasting->previewVoice($mediaId, $openId);
        //$this->wechatApp->broadcasting->previewImage($mediaId, $openId);
        //$this->wechatApp->broadcasting->previewVideo($message, $openId);
        //$this->wechatApp->broadcasting->previewCard($cardId, $openId);
        //发送预览群发消息给指定的微信号用户
        //$wxanme 是用户的微信号，比如：notovertrue
        //
        //$this->wechatApp->broadcasting->previewTextByName($text, $wxname);
        //$this->wechatApp->broadcasting->previewNewsByName($mediaId, $wxname);
        //$this->wechatApp->broadcasting->previewVoiceByName($mediaId, $wxname);
        //$this->wechatApp->broadcasting->previewImageByName($mediaId, $wxname);
        //$this->wechatApp->broadcasting->previewVideoByName($message, $wxname);
        //$this->wechatApp->broadcasting->previewCardByName($cardId, $wxname);

        $type = $info->type;
        switch ($type){
            case 'text':
                $res = $this->wechatApp->broadcasting->previewTextByName($info->media_id,$wxname);
                break;

            case 'image':

                $res = $this->wechatApp->broadcasting->previewImageByName($info->media_id, $wxname);

                break;

            case 'news':
                $res = $this->wechatApp->broadcasting->previewNewsByName($info->media_id, $wxname);

                break;
            case 'video':
                $res = $this->wechatApp->broadcasting->previewVideoByName($info->media_id, $wxname);


                break;
            case 'voice':
                $res = $this->wechatApp->broadcasting->previewVoiceByName($info->media_id, $wxname);
                break;
            case 'card':
                $res = $this->wechatApp->broadcasting->previewCardByName($info->media_id, $wxname);
                break;
            default:
                $res = $this->wechatApp->broadcasting->previewTextByName($info->media_id,$wxname);

                break;
        }

        return $res;

    }

    protected function sendAll($info){


        $type = $info->type;
        switch ($type){

            case 'image':

                $res = $this->wechatApp->broadcasting->sendImage($info->media_id);

                break;

            case 'news':
                $res = $this->wechatApp->broadcasting->sendNews($info->media_id);

                break;
            case 'video':
                $res = $this->wechatApp->broadcasting->sendVideo($info->media_id);


                break;
            case 'voice':
                $res = $this->wechatApp->broadcasting->sendVoice($info->media_id);
                break;
            case 'card':
                $res = $this->wechatApp->broadcasting->sendCard($info->media_id);
                break;
            default:
                $res = $this->wechatApp->broadcasting->image($info->media_id);

                break;
        }
        return $res;

    }


    /**
     ************************二维码设置**************************
     */
    public function qrcode(){
        if (Request::isPost()) {
            $list = Db::name('wx_qrcode')->select()->toArray();
            return $result = ['code' => 0, 'msg' =>lang('get info success'), 'data' => $list,];
        }
        return view();
    }

    public function qrcodeAdd(){
        if(Request::isPost()){
            $data = Request::param();
            if($data['type']==0){
                $data['expire_seconds'] = $data['expire_seconds']?$data['expire_seconds']:2592000;
                $res = $this->wechatApp->qrcode->temporary('foo',$data['expire_seconds']);
            }else{
                $res = $this->wechatApp->qrcode->forever('foo');// 或者 $app->qrcode->forever(56);
            }
            $this->showError($res);
            $data['store_id'] = $this->wechatAccount->id;
            $data['wx_aid'] = $this->store_id;
            $data['ticket'] = $res['ticket'];
            $data['url'] = $res['url'];
            $data['qrcode'] = $url = $this->wechatApp->qrcode->url($res['ticket']);
            if(Db::name('wx_qrcode')->insert($data)){
                $this->success(lang('add success'));
            }else{
                $this->error(lang('add fail'));
            }

        }
        $view = ['title'=>lang('add'),
            'info'=>''];
        View::assign($view);
        return view();
    }


    public function qrcodeState(){
        if(Request::isPost()){
            $id = Request::param('id');
            $qr = Db::name('wx_qrcode')->find($id);
            $status = $qr['status']==1?0:1;

            $res = Db::name('wx_qrcode')->where('id',$qr['id'])->update(['status'=>$status]);
            if($res){
                $this->success(lang('edit success'));
            }else{
                $this->error(lang('edit fail'));
            }
        }
        $view = ['title'=>lang('add'),
            'info'=>''];
        View::assign($view);
        return view();
    }

    public function qrcodeDel(){
        if(Request::isPost()) {
            $id = Request::param('id');
            $res = Db::name('wx_qrcode')->delete($id);
            if($res){
                $this->success(lang('delete success'));
            }else{
                $this->error(lang('delete fail'));
            }
        }
    }


    /**
     ************************回复设置***************************
     */
    public function reply(){

        $type = Request::get('type','default');
        $typeList = [
            [
                'url' => url('reply',['type'=>'default']),
                'item' => "默认回复",
                "type" => 'default'
            ],
            [    'url' => url('reply',['type'=>'subscribe']),
                'item' => "关注回复",
                "type" => 'subscribe'
            ],

            [ 'url' => url('reply',['type'=>'keyword']),
                'item' => "关键字回复",
                "type" =>'keyword'
            ],

           ];


        if ($type == 'default') {

            $info = Db::name('wx_reply')
                ->where($this->where)
                ->where('type', $type)
                ->select();
        } elseif ($type == 'subscribe') {
            $info = Db::name('wx_reply')
                ->where($this->where)
                ->where('type' ,$type)
                ->select
                ();

        } elseif($type == 'keyword') {
            $info = Db::name('wx_reply') ->where($this->where)
                ->where('type' ,$type)
                ->select();
        }
        $view = [
            'title'=>'粉丝',
            'type'=>$type,
            'info' =>$info,
            'typeList'=>$typeList,
            ];
        View::assign($view);
        return view();


    }

    public function replyAdd(){

        if(Request::isPost()){
            $data = Request::post();
            $data['store_id'] = $this->store_id;
            $data['wx_aid'] = $this->wechatAccount->id;
            if(!$data['type']){
                $data['type']='keyword';
            }
            if($data['data']){
                $data['msg_type'] ='text';
            }
            $res = WxReply::create($data);
            if ($res) {
                $this->success(lang('add success'),url('index'));
            } else {
                $this->error(lang('add fail'));
            }
        }

        $view = [
            'info' => [],
            'title' => lang('add'),
            'materialGroup' => $this->getMaterialGroup(),

        ];
        View::assign($view);
        return view();
        
    }

    public function replyEdit(){
        if (Request::isPost()) {
            $data = Request::post();
            $data['store_id'] = $this->store_id;
            $data['wx_aid'] = $this->wechatAccount->id;
            $res = WxReply::update($data);
            if ($res) {
                $this->success(lang('edit success'),url('index'));
            } else {
                $this->error(lang('edit fail'));
            }
        }
        $info = WxReply::find(Request::get('id'));
        $view = [
            'info' => $info,
            'title' => lang('edit'),
            'materialGroup' => $this->getMaterialGroup(),
        ];
        View::assign($view);
        return view('reply_add');

    }
    public function replyDel(){

        $id = Request::post('id');
        WxReply::destroy($id);
        $this->success(lang('delete success'));

    }



    /**
     ************************接口返回***************************
     */

    //获取素材
    public function getMaterialByType(){
        $type = Request::post('type');
//      $type text 素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）

//      $res = $this->wechatApp->material->list($type,0,100);
        $res =  WxMaterial::where($this->where)->where('type',$type)
            ->where($this->where)->select()->toArray();
        if($type=='news'){
            foreach ($res as $k=>$v){
                $res[$k]['groupList'] = WxMaterialInfo::where($this->where)->where('material_id',$v['id'])->select()->toArray();
            }
        }
        $this->success(lang('get info success'),'',$res);


    }

    /**
     * @param $type
     * @param int $id
     * @return array|\think\Collection|\think\Model|null
     * 获取素材
     */
    protected function getMaterialGroup(){
        $materialGroup = [];
        foreach ($this->materialType as $k=>$v){
            if($v=='news'){

                $weixin_material_info = Db::name('wx_material')->where('type','news')->select()->toArray();
                if (!empty($weixin_material_info)) {
                    foreach($weixin_material_info as $key=>$value){

                        $item_info = Db::name('wx_material_info')->where('material_id' , $value['id'])->select()->toArray();
                        $weixin_material_info[$key]['item_info'] = $item_info;
                    }
                }
                $materialGroup[$v] = $weixin_material_info;

            }else{

                $weixin_material_info = Db::name('wx_material')->where('type',$v)->select()->toArray();

                $materialGroup[$v] = $weixin_material_info;

            }
        }
        return $materialGroup;

    }

    /**
     ********************************上传素材接口***************************************
     */

    protected function uploads($type){

        //获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        for ($i = 0; $i < count($fileKey); $i++) {
            //获取表单上传文件
            $file = request()->file($fileKey[$i]);
            try {
                validate($type)->check(DataHelper::objToArray($file));
                $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);

                $path[] = '/storage/' . $savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
        }
        if (!empty($path)) {
            $result['code'] = 1;
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            if (Request::param('responseType') == 'json') {
                $result["url"] = $path[0];
            } else {
                $result["url"] = $path[0];
            }
            $result['msg'] = lang('upload success');
            return $result;
        } else {
            //上传失败获取错误信息
            $result['url'] = '';
            $result['msg'] = $error;
            $result['code'] = 0;
            return $result;
        }


    }
    public function imageUpload(){

        $res = $this->uploads($this->imageValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadImage('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WxMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),'',$result);
            }else{
                $this->error('上传失败');

            }
        }else{
            $this->error('上传失败');

        }
    }

    public function videoUpload(){
        $data = Request::post();
        if(!$data['url'] || !$data['file_name'] || !$data['des']){
            $this->error('数据不能为空');
        }
        $result = $this->wechatApp->material->uploadVideo('.'.$data['url'],$data['file_name'],$data['des']);
        $this->showError($result);
        $resource = $this->wechatApp->material->get($result['media_id']);
        $datas  = [
            'store_id'=> $this->store_id,
            'wx_aid'=> $this->wechatAccount->id,
            'media_id'=> $result['media_id'],
            'media_url'=> $resource['down_url'],
            'local_cover'=> $data['url'],
            'type'=> 'video',
            'file_name'=> $data['file_name'],
            'des'=> $data['des'],
        ];
        $result['url'] = $resource['down_url'];

        $r = WxMaterial::create($datas);
        if($r){
            $this->success(lang('upload success'),'',$result);
        }else{
            $this->error('上传失败');

        }


    }

    public function voiceUpload(){
        $res = $this->uploads($this->voiceValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadVoice('./'.$res['url']);
            $this->showError($result);
            $resource = $this->wechatApp->material->get($result['media_id']);

            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],

                'type'=> 'image',
            ];
            $result['url'] = $resource['down_url'];
            $r = WxMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),'',$result);
            }else{
                $this->error('上传失败');

            }
        }else{
            $this->error('上传失败');

        }

    }


    public function thumbUpload(){
        $res = $this->uploads($this->thumbValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadThumb('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WxMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),$result['url']);
            }else{
                $this->error(lang('upload fail'));

            }
        }else{
            $this->error(lang('upload fail'));

        }


    }

    public function UeditUploadImage(){

        $res = $this->uploads($this->imageValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadImage('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WxMaterial::create($data);
            $data = ['state'=>'SUCCESS','url'=>$data['media_url']];

        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);

    }

    public function UeditUploadVideo(){
        $res = $this->uploads($this->videoValidate);

        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadVideo('./'.$res['url'],$res['url'],$res['url']);
            $this->showError($result);
            $resource = $this->wechatApp->material->get($result['media_id']);

            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'video',
                'file_name'=> $res['url'],
                'des'=> $res['url'],
            ];
            $result['url'] = $resource['down_url'];
            $r = WxMaterial::create($data);

            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);

    }

    public function UeditUploaVoice(){

        $res = $this->uploads($this->voiceValidate);

        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wechatApp->material->uploadVoice('./'.$res['url']);
            $this->showError($result);
            $resource = $this->wechatApp->material->get($result['media_id']);

            $data  = [
                'store_id'=> $this->store_id,
                'wx_aid'=> $this->wechatAccount->id,
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];
            $result['url'] = $resource['down_url'];
            $r = WxMaterial::create($data);

            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);
    }
    public function getListImage(){
            $list = WxMaterial::where($this->where)->where('type','image')->select();
            $data = ['state'=>'SUCCESS','start'=>0,'total'=>count($list),'list'=>[]];
            if($list){
                foreach ($list as $k=>$v) {
                    $data['list'][$k]['url'] = $v['media_url'];
                    $data['list'][$k]['mtime'] = time();
                }
            }

            return json_encode($data);

    }
    // 微信返回数据
    protected  function showError($res){
        if(isset($res['errcode']) && $res['errcode']>0){
            $this->error($res['errmsg']);
        }

    }

    //获取媒体素材
    protected function getMaterialByMediaId($mediaId){
        $resource = $this->wechatApp->material->get($mediaId);
        $this->showError($resource);
        return $resource;

    }
}